//
//  SettingGesturePwdViewController.m
//  YTwallet
//
//  Created by ZhangLin on 2019/3/14.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "SettingGesturePwdViewController.h"
#import "SettingGesturePwdTableViewCell.h"
//设置手势密码页面
#import "GestureViewController.h"
//验证手势密码
#import "ResetGestureViewController.h"
//查看指纹是否设置过
#import "PCCircleViewConst.h"
#import "AppTools.h"
#import <LocalAuthentication/LocalAuthentication.h>
@interface SettingGesturePwdViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *Array;

@end

@implementation SettingGesturePwdViewController

-(NSMutableArray *)Array
{
    if (_Array == nil) {
        _Array = [NSMutableArray array];
    }
    return _Array;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"设置";
    self.view.backgroundColor = [UIColor colorWithRed:242 / 255.0 green:244 / 255.0 blue:246 / 255.0 alpha:1];
    //创建tableView
    [self createTableView];
}

-(void)createTableView
{
    self.Array = @[@"开启手势解锁",@"重置手势密码"].mutableCopy;
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStyleGrouped)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.tableView registerClass:[SettingGesturePwdTableViewCell class] forCellReuseIdentifier:@"cell"];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.Array.count;
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SettingGesturePwdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    //最后一个cell不显示分割线
    if (indexPath.row == self.Array.count - 1) {
        cell.lineView.hidden = YES;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.titleLab.text = self.Array[indexPath.row];
    //手势登录使用switch
    if (indexPath.row == 1) {
        cell.arrowImv.hidden = NO;
        cell.mySwitch.hidden = YES;
    }else
    {
        cell.arrowImv.hidden = YES;
        cell.mySwitch.hidden = NO;
        //switch事件
        [cell.mySwitch addTarget:self action:@selector(mySwitchAction:) forControlEvents:(UIControlEventValueChanged)];
    }
    
    if (indexPath.row == 0) {
        NSString *str = [PCCircleViewConst getGestureWithKey:gestureFinalSaveKey];
        if (str.length == 0) {
            //没有设置过手势
            cell.mySwitch.on = NO;
        }else
        {
            //设置过手势
            cell.mySwitch.on = YES;
        }
    }
    
    
    return cell;
}

-(void)mySwitchAction:(UISwitch *)sender
{
    if (sender.on) {
        NSLog(@"打开手势登录");
        //先判断指纹是否开启状态
        if ([AppTools isOpenedFingerprint]) {
            [self TouchIdWithType:@"close"];
            
        }else
        {
            GestureViewController *gestureVC = [[GestureViewController alloc] init];
            gestureVC.type = GestureViewControllerTypeSetting;
            [self.navigationController pushViewController:gestureVC animated:YES];
        }
        
        
        
    }else
    {
        NSLog(@"关闭手势登录");
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定关闭手势登录?" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"关闭" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            //验证自身
            ResetGestureViewController *resetVc = [[ResetGestureViewController alloc] init];
            [resetVc setType:(closeGesture)];
            [self.navigationController pushViewController:resetVc animated:YES];
        }];
        
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            //不做处理
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            SettingGesturePwdTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            cell.mySwitch.on = YES;
        }];
        [alertVC addAction:okAction];
        [alertVC addAction:cancleAction];
        [self presentViewController:alertVC animated:YES completion:nil];
        
        
        
        
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击了tableView");
    if (indexPath.section == 0 && indexPath.row == 1) {
        NSLog(@"重置手势密码");
        NSString *str = [PCCircleViewConst getGestureWithKey:gestureFinalSaveKey];
        if (str.length == 0) {
            [self showFailedResultTips:@"请先开启手势解锁" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        }else{
            ResetGestureViewController *resetGestureVC = [[ResetGestureViewController alloc] init];
            [resetGestureVC setType:ResetGesture];
            [self.navigationController pushViewController:resetGestureVC animated:YES];
        }   
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10.0f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.01)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

-(void)TouchIdWithType:(NSString *)type
{
    NSString *version = [UIDevice currentDevice].systemVersion;
    if ([version integerValue] < 8.0) {
        NSLog(@"系统版本不支持TouchID");
        //开通指纹失败
        return;
    }
    LAContext *context = [[LAContext alloc] init];
    context.localizedFallbackTitle = @"";
    NSError *error = nil;
    
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"通过Home键验证已有手机指纹" reply:^(BOOL success, NSError * _Nullable error) {
            
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"TouchID 验证成功");
                   
                    if ([type isEqualToString:@"close"]) {
                        //跳转手势页面
                        GestureViewController *gesture = [[GestureViewController alloc] init];
                        [gesture setType:GestureViewControllerTypeSetting];
                        [self.navigationController pushViewController:gesture animated:YES];
                    }
                    
                    
                    
                    
                });
            }else if(error){
                //开通指纹失败
                
                
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showFailedResultTips:@"验证失败,无法开启手势登录" animated:YES forSeconds:2 completionBlock:^{
                        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                        SettingGesturePwdTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                        cell.mySwitch.on = NO;
                        [self.tableView reloadData];
                        [PCCircleViewConst saveGesture:@"" Key:gestureFinalSaveKey];
                    }];
                    
                });
                
                
                
                
                switch (error.code) {
                    case LAErrorAuthenticationFailed:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 验证失败");
                            //当第三次的时候系统会提示验证失败
                            [self showFailedResultTips:@"验证失败" animated:YES forSeconds:1.5];
                        });
                        break;
                    }
                    case LAErrorUserCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 被用户手动取消");
                        });
                    }
                        break;
                    case LAErrorUserFallback:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"用户不使用TouchID,选择手动输入密码");
                        });
                    }
                        break;
                    case LAErrorSystemCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 被系统取消 (如遇到来电,锁屏,按了Home键等)");
                        });
                    }
                        break;
                    case LAErrorPasscodeNotSet:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 无法启动,因为用户没有设置密码");
                        });
                    }
                        break;
                    case LAErrorTouchIDNotEnrolled:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 无法启动,因为用户没有设置TouchID");
                        });
                    }
                        break;
                    case LAErrorTouchIDNotAvailable:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 无效");
                        });
                    }
                        break;
                    case LAErrorTouchIDLockout:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self openSystemPassword];
                            NSLog(@"TouchID 被锁定(连续多次验证TouchID失败,系统需要用户手动输入密码)");
                        });
                    }
                        break;
                    case LAErrorAppCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"当前软件被挂起并取消了授权 (如App进入了后台等)");
                        });
                    }
                        break;
                    case LAErrorInvalidContext:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"当前软件被挂起并取消了授权 (LAContext对象无效)");
                        });
                    }
                        break;
                    default:
                        break;
                }
            }
        }];
        
    }else{
        NSLog(@"当前设备不支持TouchID");
        dispatch_async(dispatch_get_main_queue(), ^{
            [PCCircleViewConst saveGesture:@"" Key:gestureFinalSaveKey];
        });
        
        //打开系统密码
        [self openSystemPassword];
    }
}

-(void)openSystemPassword
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        LAContext *myContext=[[LAContext alloc] init];
        NSError *error=nil;
        
        if([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error])
        {
            [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:@"通过Home键验证已有手机指纹" reply:^(BOOL success, NSError * _Nullable error) {
                
            }];
            
        }
    });
}

@end
